package com.iwop.moto.controller;

import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.model.FCouponLimit;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.model.User;
import com.iwop.moto.service.FCouponLimitService;
import com.iwop.moto.service.MCouponService;
import com.iwop.moto.service.UserService;
import com.iwop.moto.utils.stringUtil.ObjectId;
import com.iwop.moto.utils.stringUtil.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chenzhongqiang on 2016/11/3.
 */

@Controller
public class MCouponController extends BaseController {

    @Autowired
    MCouponService mCouponService;
    @Autowired
    UserService userService;
    @Autowired
    FCouponLimitService fCouponLimitService;

    Logger logger = Logger.getLogger(MCouponController.class);


    @RequestMapping("/api/coupon/add")
    @ResponseBody
    public ResultModel mgoodsAdd() {
        SuperRecordModel superRecordModel = this.getSRModel();
        superRecordModel.put("sid", ObjectId.UUID());
        superRecordModel.put("status_falg", "1");
        superRecordModel.put("types", "2");
        mCouponService.addCoupon(superRecordModel);
        return null;
    }

    /**
     * H5页面优惠券列表
     *
     * @return
     */
    @RequestMapping("/api/coupon/list")
    @ResponseBody
    public ResultModel mgoodsList() {
        try {
            SuperRecordModel superRecordModel = this.getSRModel();
            superRecordModel.put("user_id", superRecordModel.getString("session_id"));
            List<SuperRecordModel> userCouponBy = mCouponService.getUserCouponBy(superRecordModel);
            return getSucceed(userCouponBy, ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


    /**
     * 支付前过滤可选用抵用券
     *
     * @param session_id  用户id
     * @param payMoney    支付金额
     * @param client_type (user 用户;business 商家)
     * @return 可使用的抵用券信息和张数
     */
    @RequestMapping("/consumer/payAction")
    @ResponseBody
    public ResultModel payAction() {
        try {
            SuperRecordModel superRecordModel = this.getSRModel();
            String user_id = superRecordModel.getString("session_id");
            double payMoney = Double.parseDouble(String.valueOf(superRecordModel.get("payMoney")));
            String clientType = superRecordModel.getString("client_type");
            if (StringUtils.isEmpty(clientType) || "".equals(clientType)) {
                return reUserCoupon(user_id, payMoney);
            }
            FCouponLimit oneByClientType = null;
            try {
                oneByClientType = fCouponLimitService.findOneByClientType(clientType);
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("FCouponLimit表配置错误，请查询");
                return reNullCoupon(user_id);
            }
            if (null == oneByClientType) {
                logger.info("FCouponLimit配置为空，不做限制");
                return reUserCoupon(user_id, payMoney);
            }
            Integer integer = getLimitInteger(user_id, oneByClientType.getLimitDay());
            if (integer >= oneByClientType.getLimitCount()) {
                return reNullCoupon(user_id);
            }
            return reUserCoupon(user_id, payMoney);
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("支付前过滤可选用抵用券出错", e);
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 返回用户可用优惠券
     *
     * @param superRecordModel
     * @param user_id          用户id
     * @param payMoney         支付金额
     * @return
     */
    public ResultModel reUserCoupon(String user_id, double payMoney) {
        SuperRecordModel superRecordModel = new SuperRecordModel();
        Map<String, Object> map = new HashMap<>();
        superRecordModel.put("user_id", user_id);
        superRecordModel.put("payMoney", payMoney);
        List<SuperRecordModel> userCouponBy = mCouponService.getUserCouponByParameter(superRecordModel);
        User user = userService.getUserBySid(user_id);
        map.put("rmoney", user.getRmoney());
        map.put("userCouponBy", userCouponBy);
        map.put("couponCount", userCouponBy.size());
        return getSucceed(map, ErrCode.SUCCEED);
    }

    /**
     * 根据客户端配置获取用户可用优惠券张数
     *
     * @param user_id  用户id
     * @param limitDay 时间限制
     * @return
     */
    public Integer getLimitInteger(String user_id, String limitDay) {
        SuperRecordModel srm = new SuperRecordModel();
        Date currentTime = new Date();
        if ("30".equals(limitDay)) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
            String status_time = formatter.format(currentTime);
            srm.put("status_time", status_time);
        } else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String status_time = formatter.format(currentTime);
            srm.put("status_time", status_time);
        }
        srm.put("status_flag", "2");
        srm.put("user_id", user_id);
        return mCouponService.fingUserCouponCountByStatus(srm);
    }

    /**
     * 返回无可用优惠券
     *
     * @param user_id 用户id
     * @return
     */
    public ResultModel reNullCoupon(String user_id) {
        Map<String, Object> map = new HashMap<>();
        List<SuperRecordModel> userCouponBy = new ArrayList<>();
        User user = userService.getUserBySid(user_id);
        map.put("rmoney", user.getRmoney());
        map.put("userCouponBy", userCouponBy);
        map.put("couponCount", 0);
        return getSucceed(map, ErrCode.SUCCEED);
    }

}
